
import { CryptoJS } from "./crypto-js.min.js"
var initData = {
    filesArr: [],
    storageFiles: [],
    token: ''
    // pointer: 0,
}
document.addEventListener('DOMContentLoaded', function() {
    const TARGET_URL_PATTERN = 'https://hailuoai.video/*';
    console.log("DOMContentLoaded");
    initSelect('size-select',[1])
    initSelect('time-select',[1])
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        let tab = tabs[0];
        let url = new URL(tab.url);
        let isTargetPage = url.href.match(TARGET_URL_PATTERN);
        let interactiveElements = document.querySelectorAll('button, input, select, textarea');
        if (!isTargetPage) {
            document.body.style.opacity = '0.5';
            document.body.style.pointerEvents = 'none';
            interactiveElements.forEach(element => element.disabled = true);
        } else {
            document.body.style.opacity = '1';
            document.body.style.pointerEvents = 'auto';
            interactiveElements.forEach(element => element.disabled = false);
            // clearSyncStorage();
            renderFiles();
            // 给content.js发送消息，获取token
            sendMessageToContentScript({type: "getToken"}, function(response) {
                console.log(response);
            })

        }
    });
})
async function renderFiles() {
    const filesStorage = await getSyncStorage();
    console.log("------filesStorage------:", filesStorage);
    initData.storageFiles = filesStorage ? filesStorage?.fileObj || [] : [];
    initData.token = filesStorage?.token;
    if(initData?.token){
        document.querySelector('.noToken').classList.add('hidden');
    }else{
        document.querySelector('.noToken').classList.remove('hidden');
        document.getElementById('upload-button').setAttribute('disabled', 'disabled');
    }
    if (initData.storageFiles && initData.storageFiles.length > 0) {
        document.getElementById('image-list').innerHTML = '';
        for (let i = 0; i < initData.storageFiles.length; i++) {
            let file = initData.storageFiles[i];
            let html = ``;
            let contentHtml= file.imgUrl ? `<img src="${file.imgUrl}" id="${file.id}" fileid="${file.fileID}" alt=""/>` : `<span>${file.desc}</span>`;
            switch (file.status) {
                case -1:
                    html += `<span class="close">x</span>`+contentHtml+`<span class="status status-1">接口异常</span>`;
                    break;
                case 0:
                    html += contentHtml + `<span class="status status0">未生成</span>`;
                    break;
                case 1:
                    html += `<span class="status status1">处理中</span>`+ contentHtml;
                    break;
                case 2:
                    html += `<span class="close">x</span>`+contentHtml+`<span class="status status2">已生成</span>`;
                    break;
                case 3:
                    html += `<span class="close">x</span>`+contentHtml+`<span class="status status3">不合格</span>`;
                    break;
                case 4:
                    html += `<span class="close">x</span>`+contentHtml+`<span class="status status4">其他异常</span>`;
                    break;
                default:
                    break;
            }
            let li = document.createElement('li');
            li.setAttribute('VideoId', file.videoId)
            li.innerHTML = html;
            document.getElementById('image-list').appendChild(li);
        };
    }
}

// chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    // console.log('request:', request)
    // sendResponse("ok")
//     if (request.type === 'saveVideo') {
//         renderFiles(true);
//     }else if (request.type === 'notLogin') {
//         document.querySelector('.noToken').classList.remove('hidden');
//         document.getElementById('upload-button').setAttribute('disabled', 'disabled');
//     }else if (request.type === 'notPointer') {
//         document.querySelector('.noPointer').classList.remove('hidden');
//     }
// });

document.getElementById('image-uploader').addEventListener('change',async function (event) {
    let files = Array.from(event.target.files);
    let typeReg = /^image\/(jpg|jpeg|png)$/i;
    let btnFileDialog = document.querySelector('.btnFileDialog');
    let moduleid = document.getElementById('module-select').value;
    let sizeid = document.getElementById('size-select').value;
    let timeid = document.getElementById('time-select').value;
    let textAreaDescribeVal = document.getElementById('textAreaDescribe').value;
    let textItemArr = analyticalText(textAreaDescribeVal,'》');
    for(let file of files){
        if (file) {
            if(file.size > 1024 * 1024 * 20){
                alert('图片上传失败，图片大小不超过20M');
                continue;
            }
            if(!typeReg.test(file.type)){
                alert('图片上传失败，图片格式需为 jpg/jpeg/png');
                continue;
            }
            const reader = new FileReader();
            reader.onloadend = function (e) {
                let objBlob = e.target.result;
                const img = new Image();
                img.src = objBlob;
                img.onload = function () {
                    let width = parseInt(img.width);
                    let height = parseInt(img.height);
                    if((Math.min(width, height)) < 300){
                        alert('图片上传失败，图片短边像素需不少于 300像素');
                        return false;
                    }
                    if(!(width/height < 0.4 || width/height > 2.5 || height/width < 0.4 || height/width > 2.5)){
                        const fileBlob = base64ToBlob(objBlob, file.type);
                        var blobUrl = URL.createObjectURL(fileBlob);
                        
                        for(let jj in textItemArr){
                            let textItem = textItemArr[jj];
                            let descText = textItem.text;
                            let forCount = textItem.num;
                            let fileObj = {
                                id: CryptoJS.MD5(descText + jj).toString(),
                                type: file.type,
                                name: file.name,
                                desc: descText,
                                base64: objBlob,
                                moduleid: moduleid,
                                sizeid: sizeid,
                                timeid: timeid,
                                forCount: forCount
                            }
                            var i = forCount;
                            while (i > 0) {
                                i--   
                                let html = `
                                    <span class="close">x</span>    
                                    <img src="${blobUrl}" title="${descText}" name=${file.name}/>
                                `;
                                let li = document.createElement('li');
                                li.innerHTML = html;
                                document.getElementById('image-list').appendChild(li);
                            }
                            initData.filesArr.push(fileObj);
                            
                            btnFileDialog.classList.add('hidden');
                        }
                        console.log("initData.filesArr---:",initData.filesArr);
                        
                    }else{
                        alert('图片上传失败，图片长宽比例需在 0.4-2.5 之间');
                        return false;
                    }
                };
            };
            reader.readAsDataURL(file);
        }
    };
    if(initData.filesArr.length > 0 && initData.token){
        document.getElementById('upload-button').removeAttribute('disabled');
    }
});

document.getElementById('module-select').addEventListener('change',async function (event) {
    let moduleid = document.getElementById('module-select').value;
    if(moduleid == "23210"){
        initSelect('size-select',[3,2])
        initSelect('time-select',[1,4])
    }else{
        initSelect('size-select',[1])
        initSelect('time-select',[1])
    }
});
document.getElementById('size-select').addEventListener('change',async function (event) {
    let val = event.target.value;
    if(val == 2){
        initSelect('time-select',[1])
    }else{
        initSelect('time-select',[1,4])
    }
})
document.getElementById('time-select').addEventListener('change',async function (event) {
    let val = event.target.value;
    if(val == 4){
        initSelect('size-select',[3])
    }else{
        initSelect('size-select',[3,2])
    }
})


function initSelect(domId,valShow){
        let domSelect = document.getElementById(domId);
        let domSelectOptions = domSelect.querySelectorAll('option');
        for(let i = 0; i < domSelectOptions.length; i++){
            if( valShow.includes(Number(domSelectOptions[i].value)) ){
                domSelectOptions[i].style.display = "block";
            }else{
                domSelectOptions[i].style.display = "none";
            }
        }
        domSelect.value = valShow[0];
}



document.getElementById('t2v-uploader').addEventListener('click',async function (event) {
    let btnFileDialog = document.querySelector('.btnFileDialog');
    let moduleid2 = document.getElementById('module-select2').value;
    let ttvAreaDescribe = document.getElementById('ttvAreaDescribe').value;
    let textItemArr = analyticalText(ttvAreaDescribe,'》');
    console.log("textItemArr-t2v:",textItemArr);
    
        for(let jj in textItemArr){
            let textItem = textItemArr[jj];
            let descText = textItem.text;
            let forCount = textItem.num;
            let fileObj = {
                id: CryptoJS.MD5(descText + jj).toString(),
                desc: descText,
                base64: "",
                moduleid: moduleid2,
                forCount: forCount
            }
            var i = forCount;
            while (i > 0) {
                i--   
                let html = `
                    <span class="close">x</span>    
                    <span>${descText}</span>
                `;
                let li = document.createElement('li');
                li.innerHTML = html;
                document.getElementById('image-list').appendChild(li);
            }
            initData.filesArr.push(fileObj);
            
            btnFileDialog.classList.add('hidden');
        }
        console.log("initData.filesArr---:",initData.filesArr);
    
    if(initData.filesArr.length > 0 && initData.token){
        document.getElementById('upload-button').removeAttribute('disabled');
    }
});

document.getElementById('S2V-image-uploader').addEventListener('change',async function (event) {
    let files = Array.from(event.target.files);
    let typeReg = /^image\/(jpg|jpeg|png)$/i;
    let btnFileDialog = document.querySelector('.btnFileDialog');
    let moduleid = document.getElementById('module-select3').value;
    let srbAreaDescribe = document.getElementById('srbAreaDescribe').value;
    let textItemArr = analyticalText(srbAreaDescribe,'》');
    console.log("files:",files);
    console.log("textItemArr:",textItemArr);
    
    for(let file of files){
        if (file) {
            if(file.size > 1024 * 1024 * 20){
                alert('图片上传失败，图片大小不超过20M');
                continue;
            }
            if(!typeReg.test(file.type)){
                alert('图片上传失败，图片格式需为 jpg/jpeg/png');
                continue;
            }
            const reader = new FileReader();
            reader.onloadend = function (e) {
                let objBlob = e.target.result;
                const img = new Image();
                img.src = objBlob;
                img.onload = function () {
                    let width = parseInt(img.width);
                    let height = parseInt(img.height);
                    if((Math.min(width, height)) < 300){
                        alert('图片上传失败，图片短边像素需不少于 300像素');
                        return false;
                    }
                    if(!(width/height < 0.4 || width/height > 2.5 || height/width < 0.4 || height/width > 2.5)){
                        const fileBlob = base64ToBlob(objBlob, file.type);
                        var blobUrl = URL.createObjectURL(fileBlob);
                        
                        for(let textItem of textItemArr){
                            let descText = textItem.text;
                            let forCount = textItem.num;
                            let fileObj = {
                                type: file.type,
                                name: file.name,
                                desc: descText,
                                base64: objBlob,
                                moduleid: moduleid,
                                forCount: forCount
                            }
                            var i = forCount;
                            while (i > 0) {
                                i--   
                                let html = `
                                    <span class="close">x</span>    
                                    <img src="${blobUrl}" title="${descText}" name=${file.name}/>
                                `;
                                let li = document.createElement('li');
                                li.innerHTML = html;
                                document.getElementById('image-list').appendChild(li);
                            }
                            initData.filesArr.push(fileObj);
                            
                            btnFileDialog.classList.add('hidden');
                        }
                        console.log("initData.filesArr---:",initData.filesArr);
                        
                    }else{
                        alert('图片上传失败，图片长宽比例需在 0.4-2.5 之间');
                        return false;
                    }
                };
            };
            reader.readAsDataURL(file);
        }
    };
    if(initData.filesArr.length > 0 && initData.token){
        document.getElementById('upload-button').removeAttribute('disabled');
    }
});

function analyticalText(text,divider){
    if(!text){
        return '';
    }
    const arrTextAndNum = text.split(divider).map(item => {
        return item.trim();
    });
    const valNumArr = arrTextAndNum.map(item => {
        if(item.indexOf(':') > -1){
            let arr = item.split(':');
            if(arr.length == 2){
                let text = arr[0].trim();
                let num = isNaN(arr[1].trim()) ? 0 : Number(arr[1].trim());
                if(text && num){
                    return {
                        text,
                        num
                    }
                }
            }
        }else{
            return false
        }
    })
    return valNumArr.filter(item => item);
}

document.getElementById('upload-button').addEventListener('click', function () {
    // 添加class loading
    this.classList.add("loading")
    this.innerText = "请稍等……"
    let newFiles = sortImg(initData.filesArr);
    chrome.runtime.sendMessage({ action: 'printFiles', data: newFiles }, function (response) { 
        let t = setInterval(async function(){
            const token = await getSyncStorage("token");
            if(token){
                const filesUploaded = await getSyncStorage("filesUploaded");
                if(filesUploaded){
                    document.getElementById('upload-button').classList.remove("loading");
                    document.getElementById('upload-button').innerText = "上传成功";
                    renderFiles();
                    initData.filesArr = [];
                    clearInterval(t);
                }
            }else{
                alert("获取token接口失败，请关闭弹窗重试")
                initData.filesArr = [];
                document.getElementById('upload-button').innerText = "上传图片";
                clearInterval(t);
            }
        }, 3000);
    });
});
function sortImg(files){
    // 对图片进行排序
    // let files = JSON.parse(JSON.stringify(initData.filesArr));
    if(files.length < 2){
        return files;
    }
    let newFiles = [];
    let nameArr = [...new Set(files.map(item => item.name))];

    for(let name of nameArr){
        let fileArr = files.filter(item => item.name === name);
        newFiles.push(...fileArr)
    }
    return newFiles;
}

document.getElementById('image-list').addEventListener('click', function (event) {
    if (event.target.classList.contains('close')) {
        let li = event.target.parentElement;
        let index = initData.storageFiles.findIndex(item => item.id === event.target.nextElementSibling.id)
        if(index !== -1){
            initData.storageFiles.splice(index, 1);
            setSyncStorage({ "fileObj": initData.storageFiles })
            console.log("initData.storageFiles:",initData.storageFiles);
            
        }else{
            console.log("initData.filesArr---:",initData.filesArr);
            let idx = initData.filesArr.findIndex(item => item.name == event.target.nextElementSibling.name);
            console.log("event.target.nextElementSibling.name:",event.target.nextElementSibling.name);
            initData.filesArr.splice(idx, 1);
            document.getElementById('image-uploader').value = null;
        }
        li.remove();
    }
});
document.getElementById('openFileDom').addEventListener('click', function (event) {
    // 显示btnFileDialog
    let btnFileDialog = document.querySelector('.btnFileDialog');
    if(btnFileDialog.classList.contains('hidden')){
        btnFileDialog.classList.remove('hidden');
    }
})
document.querySelector('.btnFileDialog').addEventListener('click', function (event) {
    if (event.target.classList.contains('close1')) {
        this.classList.add('hidden');
    }
});

document.getElementById('delete-button').addEventListener('click', function (event) {
    // 显示btnFileDialog
    const sureDel = window.confirm("确定删除所有已处理图片？");
    if(!sureDel){
        return;
    }
    let deleteAArr = initData.storageFiles.filter(item => {
        if(item.status == 0 || item.status == 1){
            return item;
        }
    })
    setSyncStorage({ "fileObj": deleteAArr })
    renderFiles();
})

document.querySelector(".tabBox").addEventListener("click",function(){
    if (event.target.classList.contains('tab')) {
        let that = event.target;
        let id = that.dataset.id;
        if (that.classList.contains('active')) {
            return;
        } else {
            document.querySelectorAll('.tab').forEach(item => {
                item.classList.remove('active');
            })
            that.classList.add('active');
            document.querySelectorAll('.tabContentItem').forEach(item => {
                item.classList.remove('active');
            })
            document.getElementById(id).classList.add('active');
        }
    }
})



function base64ToBlob(base64, mimeType) {
    const byteCharacters = atob(base64.split(',')[1]);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        const slice = byteCharacters.slice(offset, offset + 512);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays, {
        type: mimeType
    });
}
const setSyncStorage = (obj) => {
    return new Promise((resolve) => {
        chrome.storage.local.set(obj, () => {
            resolve();
        });
    });
}
const getSyncStorage = (key) => {
    return new Promise((resolve) => {
        chrome.storage.local.get(key, (item) => {
            key ? resolve(item[key]) : resolve(item);
        });
    });
}
const clearSyncStorage = () => {
    return new Promise((resolve) => {
        chrome.storage.local.clear(() => {
            resolve();
        });
    });
}
const removeSyncStorage = (key) => {
    return new Promise((resolve) => {
        chrome.storage.local.remove(key, () => {
            resolve();
        });
    });
}// 向content-script主动发送消息

async function sendMessageToContentScript (message, callback) {
    let tabId = await getCurrentTab();
    if(tabId){
        const targetUrlPattern = /^https:\/\/hailuoai\.video\/?/;
        let isInActiveTab = targetUrlPattern.test(tabId.url);
        if(isInActiveTab){
            chrome.tabs.sendMessage(tabId.id, message, callback);
        }
    }

}
async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    return tab;
}